<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="年份" prop="year" style="width: 238px;">
              <el-date-picker
                v-model="queryParams.year"
                type="year"
                value-format="YYYY"
                date-format="YYYY"
              />
            </el-form-item>
            <el-form-item label="预算部门" prop="deptCode">
              <el-input :placeholder="queryParams.deptName" disabled class="with-common-170" />
            </el-form-item>
            <el-form-item label="院区" prop="yardCode">
              <el-select v-model="queryParams.yardCode" placeholder="全部" clearable class="with-common-170">
                <el-option v-for="dict in yard_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算类型" prop="budgetType">
              <el-select v-model="queryParams.budgetType" placeholder="全部" clearable class="with-common-170">
                <el-option v-for="dict in budget_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="调整类型" prop="adjustType">
              <el-select v-model="queryParams.adjustType" placeholder="全部" clearable class="with-common-170">
                <el-option v-for="dict in adjust_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['fill:adjust:add']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['fill:adjust:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table border v-loading="loading" :data="adjustList" class="enhanced-table">
        <el-table-column label="预算部门编码" align="center" prop="deptCode" />
        <el-table-column label="预算部门名称" align="center" prop="deptName" />
        <el-table-column label="院区" align="center" prop="yardCode">
          <template #default="scope">
            <dict-tag :options="yard_type" :value="scope.row.yardCode" />
          </template>
        </el-table-column>
        <el-table-column label="申请总额" align="center" prop="applyMoney" />
        <el-table-column label="调整类型" align="center" prop="adjustType">
          <template #default="scope">
            <dict-tag :options="adjust_type" :value="scope.row.adjustType" />
          </template>
        </el-table-column>
        <el-table-column label="预算类型" align="center" prop="budgetType">
          <template #default="scope">
            <dict-tag :options="budget_type" :value="scope.row.budgetType" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="approval_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" prop="createTime" width="180">
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="columnLength">
          <template #default="scope">
            <el-tooltip content="查看" placement="top">
              <el-button link type="primary" icon="View" @click="handleView(scope.row)" />
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.status === null || scope.row.status==='draft'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['fill:adjust:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="scope.row.status === null || scope.row.status==='draft'">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['fill:adjust:remove']" />
            </el-tooltip>
            <el-tooltip content="查看附件" placement="top" v-if="scope.row.ossId != null">
              <el-button type="success" circle link @click="handleViewFile(scope.row)">
                <svg-icon icon-class="excel2" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="上传" placement="top" v-if="scope.row.status!='draft'&& scope.row.ossId===null">
              <el-button type="primary" circle link @click="handleFile(scope.row)">
                <svg-icon icon-class="UploadRounded" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="下载" placement="top" v-if="scope.row.status!='draft'&& scope.row.ossId!=null">
              <el-button type="primary" circle link @click="handleDownload(scope.row)">
                <svg-icon icon-class="SymbolsDownload" />
              </el-button>
            </el-tooltip>
            <el-tooltip content="删除文件" placement="top" v-if="scope.row.status!='draft'&& scope.row.ossId!=null">
              <el-button type="danger" circle link @click="handleDeleteFile(scope.row)">
                <svg-icon icon-class="DeleteOutline" />
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 上传文件弹窗 -->
    <el-dialog v-model="dialogFile.visible" :title="dialogFile.title" style="width: 350px" append-to-body>
      <el-form ref="ossFormRef" label-width="80px">
        <el-form-item label="文件：">
          <el-upload
            ref="upload"
            class="upload-demo"
            :limit="1"
            :auto-upload="false"
            :show-file-list="true"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-change="handleFileChange"
          >
            <template #trigger>
              <el-button type="primary">请选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="success" @click="submitUpload">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Adjust" lang="ts">
import { delAdjust, deleteFile, listAdjust, uploadApplyFile } from "@/api/fill/adjust";
import { AdjustQuery, AdjustVO } from "@/api/fill/adjust/types";
import { getYear } from "@/hooks/useDate";
import { getUser } from "@/api/fill/apply";
import { genFileId, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { ref } from "vue";


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  yard_type,
  adjust_type,
  budget_type,
  approval_status
} = toRefs<any>(proxy?.useDict("yard_type", "adjust_type", "budget_type", "approval_status"));


const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<AdjustQuery>({
  pageNum: 1,
  pageSize: 10,
  deptCode: undefined,
  deptName: "暂无部门",
  yardCode: undefined,
  year: getYear(),
  adjustType: undefined,
  budgetType: undefined
});

/*调整申请列表*/
const adjustList = ref<AdjustVO[]>([]);
/** 查询预算调整主列表 */
const getList = async () => {
  loading.value = true;
  getUser().then(res => {
    let user = res.data;
    queryParams.value.deptName = user.budgetDeptName;
    queryParams.value.deptCode = user.budgetDeptCode;
  }).then(() => {
    listAdjust(queryParams.value).then(res => {
      adjustList.value = res.data.records;
      total.value = res.data.total;
    }).then(() => {
      for (let item of adjustList.value) {
        columnLength.value = 140;
        if (item.ossId != null) {
          columnLength.value = 190;
          break;
        }
      }
    });
  }).finally(() => loading.value = false);
};


/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  if (!queryParams.value.deptCode) {
    proxy?.$modal.msgError("暂无部门，不能进行申请！");
    return;
  }

  proxy.$router.push({
    path: `/fill/adjust/adjustForm/index`,
    query: {
      type: "add",
      year: queryParams.value.year,
      deptCode: queryParams.value.deptCode,
      deptName: queryParams.value.deptName,
      yardCode: queryParams.value.yardCode
    }
  });

};

/** 修改按钮操作 */
const handleUpdate = (row?: AdjustVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/fill/adjust/adjustForm/index`,
    query: {
      id: row.id,
      type: "update"
    }
  });
};
/**
 * 查看详情
 * @param row
 */
const handleView = (row?: AdjustVO) => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/fill/adjust/adjustForm/index`,
    query: {
      id: row.id,
      type: "view"
    }
  });
};


/** 删除按钮操作 */
const handleDelete = async (row?: AdjustVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm("是否确认删除选重点的数据项？").finally(() => loading.value = false);
  await delAdjust(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("fill/adjust/export", {
    ...queryParams.value
  }, `预算调整申请.xlsx`);
};
const columnLength = ref(140);
/**----------------------------------文件-----------------------------------------------*/
// 打开文件连接
const handleViewFile = (row: AdjustVO) => {
  window.open(row.url, "_blank");
};
const buttonLoading = ref(false);
const dialogFile = reactive<DialogOption>({
  visible: false,
  title: ""
});
const ossFormRef = ref<ElFormInstance>();
//选中的行数据
const selectRow = ref<AdjustVO>();
/** 文件按钮操作 */
const handleFile = (row?: AdjustVO) => {
  fileList.value = [];
  selectRow.value = null;
  dialogFile.visible = true;
  dialogFile.title = "上传附件";
  selectRow.value = row;
};
/** 下载按钮操作 */
const handleDownload = (row: AdjustVO) => {
  proxy?.$download.oss(row.ossId);
};
const fileList = ref<any[]>([]);
const selectedFile = ref<any>();
const beforeUpload = (file: File) => {

};
const handleFileChange = (file: any) => {
  // 存储选中的文件
  selectedFile.value = file;
};

const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};
/**提交*/
const submitUpload = async () => {
  if (selectedFile.value) {
    const formData = new FormData();
    formData.append("file", selectedFile.value.raw);
    formData.append("id", selectRow.value.id.toString());
    await uploadApplyFile(formData).then((res) => {
      dialogFile.visible = false;
      ElMessage.success("上传成功");
      getList();
    });
  } else {
    ElMessage.error("请选择一个文件");
  }
};

/**上传取消*/
function cancel() {
  dialogFile.visible = false;
}

const handleDeleteFile = async (row?: AdjustVO) => {
  const ossId = row?.ossId;
  await proxy?.$modal.confirm("是否确认删除附件？");
  loading.value = true;
  await deleteFile(ossId).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess("删除成功");
};
/**------------------------------------------------------------------------------------*/

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
@import "@/assets/styles/common-style";
@import "@/assets/styles/tables-style";

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

</style>
